package com.joney.mq.config;

import com.joney.mq.pojo.Content;
import com.joney.mq.pojo.ObjectMsg;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.Serializable;
import java.util.Map;

/**
 * @author wangxianchen
 * @create 2018-03-07
 * @desc 其实老老实实传JSON最方便了
 */
public class MyMessageConverter implements MessageConverter {

    public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
        if(object instanceof String){
            ActiveMQTextMessage msg = (ActiveMQTextMessage)session.createTextMessage();
            msg.setText(object.toString());
            return msg;
        }else if(object instanceof ObjectMsg){
            ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
            msg.setObject((Serializable) object);
            return msg;
        }
       // System.out.println("sendMessage:"+object.toString());
       // ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
       // msg.setObject((Serializable) object);
        return null;
    }

    public Object fromMessage(Message message) throws JMSException,MessageConversionException {
        if(message instanceof ActiveMQObjectMessage){
            ActiveMQObjectMessage msg = (ActiveMQObjectMessage) message;
            return msg.getObject();
        }else if(message instanceof ActiveMQMapMessage){
            ActiveMQMapMessage msg = (ActiveMQMapMessage)message;
            return msg.getContentMap();
        }else if(message instanceof ActiveMQTextMessage){
            ActiveMQTextMessage msg = (ActiveMQTextMessage)message;
            return msg.getText();
        }
        return null;
    }
}
